<template>
    <div>
        <!-- 查询表单 -->
        <el-form :inline="true" :model="query">
            <el-form-item label="姓名">
                <el-input v-model="query.name" placeholder="请输入搜索姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="电话">
                <el-input v-model="query.phone" placeholder="请输入电话" clearable></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="query.status" placeholder="全部" clearable>
                    <el-option label="启用" value="0"></el-option>
                    <el-option label="禁用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loadUsers">查询</el-button>
                <el-button type="success" @click="handleAdd">添加</el-button>
                <el-button type="danger" @click="delBatch">批量删除</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="users" style="width: 100%" stripe border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="80" />
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="name" label="姓名" width="180">
            </el-table-column>
            <el-table-column prop="phone" label="电话" width="180">
            </el-table-column>
            <el-table-column prop="address" label="地址">
            </el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" @change="updateStatus(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="query.pageNum" :page-sizes="[5, 10, 30, 50]" :page-size="query.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

        <!-- 对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" :close-on-press-escape="false"
            :close-on-click-modal="false" @close="handleDialogClose">
            <el-form :model="form" :rules="rules" ref="dialogForm">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="form.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="form.address" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'
axios.defaults.baseURL = 'http://ums.tangxiaoyang.vip/api'

export default {
    data() {
        return {
            query: {
                name: '',
                phone: '',
                status: null,
                pageNum: 1,
                pageSize: 5
            },
            users: [], // 用户数据
            total: 0, // 总条数
            dialogFormVisible: false, // 对话框的显示与隐藏
            form: {}, // 表单数据
            dialogTitle: '',
            rules: { // 表单验证规则
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                phone: [
                    { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' },
                ],
            },
            multipleSelection: [], // 选中数据

        }
    },
    created() {
        this.loadUsers();
    },
    methods: {
        // 加载用户列表
        async loadUsers() {
            const { data: res } = await axios.get('/users/queryByPage', {
                params: this.query
            })
            if (res.status === 200) {
                this.users = res.data.records
                this.total = res.data.total

                this.users.forEach(item => {
                    item.status = item.status == 0
                })
            }
        },
        // 监听页大小改变
        handleSizeChange(val) {
            this.query.pageSize = val
            this.loadUsers()
        },
        // 监听页码改变
        handleCurrentChange(val) {
            this.query.pageNum = val
            this.loadUsers()
        },
        handleAdd() {
            this.dialogFormVisible = true
            this.dialogTitle = '添加用户'
        },
        async save() {
            /**
             * 判断添加还是修改
             */
            let res;
            if (this.form.id) {
                // 修改用户
                res = await axios.put('/users/modify', this.form)
            } else {
                // 添加用户
                res = await axios.post('/users/add', this.form)
            }

            if (res.data.status === 200) {
                // 弹出消息提示
                this.$message.success('保存成功')
                // 关闭对话框
                this.dialogFormVisible = false
                // 重新加载数据
                this.loadUsers()
            } else {
                this.$message.error('保存失败:' + res.data.msg)
            }
        },
        async handleEdit(id) {
            const { data: res } = await axios.get('/users/query/' + id)
            this.form = res.data
            this.dialogFormVisible = true
            this.dialogTitle = '修改用户'
        },
        handleDelete(id) {
            this.$confirm('确定要删除该用户吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await axios.delete('/users/remove/' + id)
                if (res.status === 200) {
                    this.$message.success('删除成功')
                    this.loadUsers()
                } else {
                    this.$message.error('删除失败:' + res.msg)
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 监听对话框的关闭
        handleDialogClose() {
            this.dialogVisible = false
            this.$refs.dialogForm.resetFields() // 重置表单
        },
        // 监听复选框的改变
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 批量删除
        delBatch() {
            // 判断是否选择数据
            if (!this.multipleSelection.length) {
                this.$message.error('请选择要删除的数据')
                return
            }

            // 提示是否确定删除
            this.$confirm('确定要删除该用户吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 获取选中的id
                // let ids = []
                // this.multipleSelection.forEach(item => {
                //     ids.push(item.id)
                // })
                let ids = this.multipleSelection.map(item => item.id)
                const { data: res } = await axios.delete('/users/removeBatch', {
                    data: ids
                })
                if (res.status == 200) {
                    if (res.status === 200) {
                        this.$message.success('删除成功')

                        // 方式1
                        // this.loadUsers().then(() => {
                        //     if(this.users.length==0 && this.query.pageNum>1){
                        //         this.query.pageNum--
                        //         this.loadUsers()
                        //     }
                        // })

                        // 方式2

                    } else {
                        this.$message.error('删除失败:' + res.msg)
                    }
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 修改用户状态
        async updateStatus(user){
            const {data:res} = await axios.put(`/users/modifyStatus/${user.id}/${user.status?0:1}`)
            if(res.status === 200){
                return this.$message.success('修改成功')
            }
            this.$message.error('修改失败:' + res.msg)
        }
    }
}
</script>

<style lang="less" scoped>
.el-pagination {
    text-align: center;
}
</style>